<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import rwglService from '@/api/rwgl'
import formBox from '@/components/queryTable/form/index.vue'
import tableBox from '@/components/queryTable/table/index.vue'
import { formItems } from '../form-item'
import { useMainStore } from '@/store/main'
interface TitleItem {
  label: string
  prop: string
  width: number | null
  custom: boolean
  sort: boolean
}
interface TableItem {
  data: Array<any>
  titles: Array<TitleItem>
}
interface TableRow {
  ajBmWj: string
  gdbh: string
  bmsah: string
  ajmc: string
  dabh: string
  ajbh: string
  wjList: Array<any>
  expand: boolean
}
// 入参
const store = useMainStore()
// loading
const loading = ref<boolean>(false)
// 更多条件查询
const formLabel = ref()
onMounted(async () => {
  loading.value = true
  formLabel.value = await formItems('wjdbrw')
  loading.value = false
  // 分页
  changePageNum(1)
})

const page = ref({
  pageNum: 1,
  pageSize: 20,
  total: 0,
})
/*
 * 分页
 */
const changePageNum = (val: number) => {
  page.value.pageNum = val
  getTableData()
}

/*
 * 分页
 */
const changePageSize = (val: number) => {
  page.value.pageNum = 1
  page.value.pageSize = val
  getTableData()
}

// 查询条件
const form = ref({
  bmsah: '',
  ajmc: '',
  wjmc: '',
  rwztdm: '',
  ksrq: '',
  jsrq: '',
  rwlxdm: '',
  dwbm: store.userInfo?.dwbm,
})
const searchTable = (data: any) => {
  let newObj: any = {}
  for (const key in data) {
    if (key.endsWith('-rq')) {
      const kssj = key.replace('-rq', 'ksrq')
      const jssj = key.replace('-rq', 'jsrq')
      if (data[key]?.length) {
        newObj[kssj] = data[key][0]
        newObj[jssj] = data[key][1]
      } else {
        newObj[kssj] = ''
        newObj[jssj] = ''
      }
    }
    newObj[key] = data[key]
  }
  form.value = newObj
  getTableData()
}
/*
 * 获取表格
 */
// 表格数据
const tableData = ref<TableItem>({
  data: [],
  titles: [
    {
      label: '案件名称【部门受案号】/源文件名称',
      prop: 'ajBmWj',
      width: 400,
      custom: false,
      sort: true,
    },
    { label: '比对类型', prop: 'rwlxmc', width: null, custom: false, sort: false },
    { label: '比对状态', prop: 'clztmc', width: null, custom: false, sort: false },
    { label: '比对时间', prop: 'clrq', width: null, custom: false, sort: false },
    { label: '操作人', prop: 'clrxm', width: null, custom: false, sort: false },
    { label: '比对失败次数', prop: 'clsbcs', width: null, custom: false, sort: false },
  ],
})
const getTableData = () => {
  const params = {
    filter: form.value,
    pageNum: page.value.pageNum,
    pageSize: page.value.pageSize,
  }
  loading.value = true
  rwglService
    .queryWjdbrwglList(params)
    .then((res) => {
      if (res) {
        tableData.value.data = res.data.list.map((el) => {
          return {
            ...el,
            ajBmWj: el.ajmc,
            wjList: el.clwjList.map((item: any) => {
              return {
                ...item,
                ajBmWj: item.wjmc,
              }
            }),
            expand: false,
          }
        })
        page.value.total = res.data.total
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

/*
 * 获取表格下文书
 */
const getDataToTable = (data: TableRow) => {
  const params = {
    pageSize: pageCard.value.pageSize,
    pageNum: pageCard.value.pageNum,
    filter: {
      gdbh: data.gdbh,
      bmsah: data.bmsah,
      ywjmc: form.value.wjmc,
      clztdm: form.value.rwztdm,
      ksrq: form.value.ksrq,
      jsrq: form.value.jsrq,
      rwlxdm: form.value.wjmc,
      fhzlx: {},
    },
  }
  rwglService
    .queryWjbdrwxxxxList(params)
    .then((res) => {
      if (res.data) {
        const obj = tableData.value.data.find((el) => el.bmsah === data.bmsah)
        obj.wjList = res.data.list.map((el) => {
          return {
            ...el,
            ajBmWj: el.wjmc,
          }
        })
        pageCard.value.total = res.data.total
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

/**
 * 表格选择
 */
const multipleSelection = ref<any[]>([])
const selectionChange = (val: any[]) => {
  multipleSelection.value = val
}

/*
 * 批量重试
 */
const plcs = () => {
  const params = {
    rwxxList: multipleSelection.value.map((el) => {
      return {
        gdbh: el.gdbh,
        rwbh: el.rwbh,
      }
    }),
  }
  rwglService
    .retryBatch(params)
    .then(() => {
      ElMessage.success('操作成功')
      // 刷新列表
      getTableData()
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}
/**
 * 数据源
 */
const optionsObjs = ref<any>({})

/**
 * 折叠表格分页
 */
const pageCard = ref<any>({})
/*
 * 分页
 */
const changePageNumCard = (val: number, id: string) => {
  pageCard.value[id].pageNum = val
  const obj = tableData.value.data.find((el) => el.bmsah === id)
  if (obj) {
    getDataToTable(obj)
  }
}

/*
 * 分页
 */
const changePageSizeCard = (val: number, id: string) => {
  pageCard.value[id].pageNum = 1
  pageCard.value[id].pageSize = val
  const obj = tableData.value.data.find((el) => el.bmsah === id)
  if (obj) {
    getDataToTable(obj)
  }
}

/**
 * 里表格动态ref
 */
const expandTableRef = ref<any>({})
const setRef = (e: any, id: string) => {
  expandTableRef.value[`tableRef_${id}`] = e
}

const tableBoxRef = ref<InstanceType<typeof tableBox>>()
const rowClick = (row: any) => {
  if (multipleSelection.value?.includes(row)) {
    tableBoxRef.value?.refTable.toggleRowSelection(row, false)
  } else {
    tableBoxRef.value?.refTable.toggleRowSelection(row, true)
  }
}

defineExpose({ changePageNum })
</script>
<template>
  <div class="container" v-loading="loading">
    <!--表单-->
    <div class="form-box">
      <form-box
        ref="formBoxRef"
        :formLabel="formLabel"
        :formData="form"
        :moreShow="false"
        :optionsObj="optionsObjs"
        @searchEvent="searchTable"
      />
    </div>
    <!--按钮组-->
    <div class="btn-box">
      <div class="table-title">
        <span>文件对比任务</span>
      </div>
      <button class="btn_operation" @click="plcs" :disabled="!multipleSelection.length">
        <div class="btn-gdajjc"></div>
        批量重试
      </button>
      <button class="btn_operation" @click="changePageNum(1)">
        <div class="btn-refresh"></div>
        刷新
      </button>
    </div>
    <!--表格-->
    <div class="table-box">
      <!--  @expandChange="expandChange" -->
      <table-box
        gnbm="wjrwgl-wjdbrw"
        ref="tableBoxRef"
        :table-data="tableData"
        :selectShow="true"
        :expand="true"
        rowKey="bmsah"
        :getTableDataParam="page"
        :tableInfo="{ total: page.total }"
        @changeCurrent="changePageNum"
        @changeSize="changePageSize"
        @selectionChange="selectionChange"
        @rowClick="rowClick"
      >
        <template #expand="{ props }">
          <table-box
            gnbm="wjrwgl-wjdbrw"
            :ref="($evnet:any)=>setRef($evnet, props.row.bmsah)"
            :height="200"
            :table-data="{
              titles: tableData.titles,
              data: props.row.wjList,
            }"
            :selectShow="true"
            :showHeader="false"
            :expandChild="true"
            rowKey="wjbh"
            :getTableDataParam="pageCard[props.row.bmsah]"
            :tableInfo="{ total: pageCard[props.row.bmsah]?.total || 0 }"
            @selectionChange="selectionChange"
            @changeCurrent="changePageNumCard($event, props.row.bmsah)"
            @changeSize="changePageSizeCard($event, props.row.bmsah)"
          >
          </table-box>
        </template>
      </table-box>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .form-box {
    width: 100%;
  }
  .btn-box {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-bottom: 10px;
  }
  .table-box {
    flex: 1;
    flex-shrink: 0;
    overflow: auto;
  }
  .active-img {
    cursor: pointer;
    float: left;
  }
  .active-img + .active-img {
    margin-left: 10px;
  }
}
</style>
